//
//  EmoticonManager.swift
//  EmoticonKeyboard
//
//  Created by apple on 16/2/28.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

//加载表情的工具类
class EmoticonManager: NSObject {
    
    //加载表情模型数据 都是从静态内存中加载数据 不在从 磁盘做io操作 
    static let sharedEmoticoManager = EmoticonManager()

    lazy var packages = [EmoticonPackages]()
    
    
    private override init() {
        super.init()
        self.loadEmotions()
    }
    
    //加载表情模型数组
    func loadEmotions() {
        //1.在bundle路径下 读取对应的文件
        let path = NSBundle.mainBundle().pathForResource("emoticons", ofType: "plist", inDirectory: "Emoticons.bundle")
        guard let filePath = path else {
            print("文件路径不存在")
            return
        }
        
        let dict = NSDictionary(contentsOfFile: filePath)!
        //2.获取packeages 键下对应的数组
        guard let array = dict["packages"] as? [[String : AnyObject]] else {
            print("数据格式有问题")
            return
        }
        
        //3.遍历数组  获取对应的文件夹的id
        for item in array {
            let id = item["id"] as! String
//            print(id)
            //4.获取到id之后 使用id 去加载分组表情
            loadGroupEmoticon(id)
        }
        
    }
    
    
    //查找字符串中表情字符串 转换属性文本
    func getImageTextWithEmoticonText(str: String, font: UIFont) -> NSAttributedString {
        let pattern = "\\[.*?\\]"
        let regex = try! NSRegularExpression(pattern: pattern, options: [])
        
        //正则表达式第一个核心方法
        let result = regex.matchesInString(str, options: [], range: NSRange(location: 0, length: str.characters.count))
        
        //2.遍历查找的结果 使用每一个表情字符串 去 表情模型中 匹配对应表情模型
        //使用倒叙遍历查询的结果集
        
        let strM = NSMutableAttributedString(string: str)
        var index = result.count - 1
        //使用倒叙 只需要替换一次 更加简单
        while index >= 0 {
            let r = result[index]
            let range = r.rangeAtIndex(0)
            print(range)
            let subStr = (str as NSString).substringWithRange(range)
            print(subStr)
            //使用表情字符串 在表情数组中 去匹配对应的表情模型
            if let em = getEmoticonWithEmoticonText(subStr) {
                //如果获取的模型不为 nil
                //3.模型中包含了表情图片
                //4.将图片添加到附件中 //将附件对象转换为 属性字符串
                let imageText = EmoticonAttachment.emoticonImageToImageText(em, font: font)
                //5.完成属性字符串的替换
                strM.replaceCharactersInRange(range, withAttributedString: imageText)
            }
            index--
        }
        return strM
    }
    
    
    private func getEmoticonWithEmoticonText(subStr: String) -> Emoticon? {
        //1.获取所有的表情数组
        //遍历分组表情
        for p in packages {
            //需要在分组表中根据表情字符串 查询对应的表情模型
            //filter 滤镜  过滤
            //自省的数组类型
            let emoticons = p.emoticonList.filter({ (em) -> Bool in
                //如果满足 chs == subStr 就会被添加到对应的数组中
                return em.chs == subStr
            })
            
            if emoticons.count != 0 {
                return emoticons.last
            }
        }
        return nil
    }
    
    
    private func loadGroupEmoticon(id: String) {
        //1.获取文件路径
        let path = NSBundle.mainBundle().pathForResource("Info", ofType: "plist", inDirectory: "Emoticons.bundle/" + id)
        guard let filePath = path else {
            print("文件路径不存在")
            return
            
        }
        
        //获取到 分组文件夹下的 Info.plist 对应的字典数据
        let dict = NSDictionary(contentsOfFile: filePath)!
        
        //1.获取分组表情目录的中文名称
        let group_name_cn = dict["group_name_cn"] as! String
//        print(group_name_cn)
        
        //获取分组表情的字典类型数组
        let emoticons = dict["emoticons"] as! [[String : String]]
        
        //实例化packages模型
        let p = EmoticonPackages(id: id, name: group_name_cn, array: emoticons)
        packages.append(p)
    }
}
